<!-- 需求单分配运单 -->
<template>
  <el-dialog
    :title="type === 'add' ? '运单分配' : '修改运单'"
    :visible.sync="dialogVisible"
    append-to-body
    width="40%"
  >
    <el-form
      v-loading="loading"
      class="assignWaybill"
      ref="form"
      :model="form"
      label-width="80px"
      :rules="rules"
    >
      <div class="from-header">司机</div>
      <el-form-item label="司机" prop="driverId">
        <el-select
          v-model="form.driverId"
          filterable
          placeholder="请选择司机"
          @change="changeDriver"
          size="small"
        >
          <el-option
            v-for="item in driverList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input disabled v-model="form.phone" size="small"></el-input>
      </el-form-item>
      <el-form-item label="押运员" prop="escortId">
        <el-select
          v-model="form.escortId"
          size="small"
          filterable
          clearable
          placeholder="请选择押运员"
        >
          <el-option
            v-for="item in supercargoList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="from-header">车辆</div>
      <el-form-item label="主车号" prop="carId">
        <el-select
          v-model="form.carId"
          filterable
          size="small"
          placeholder="请选择车辆"
          @change="changeCar"
        >
          <el-option
            v-for="item in carList"
            :key="item.id"
            :label="item.carNo"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="挂车号" v-if="form.trailerNo">
        <el-input disabled v-model="form.trailerNo" size="small"></el-input>
      </el-form-item>
      <el-form-item label="挂车号" v-else>
        <el-select
          v-model="form.bindCarNo"
          filterable
          clearable
          size="small"
          placeholder="请选择挂车"
        >
          <el-option
            v-for="item in trailerList"
            :key="item.id"
            :label="item.bindCarNo"
            :value="item.bindCarNo"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="罐箱类型" prop="tankType">
        <el-select
          v-model="form.tankType"
          filterable
          size="small"
          placeholder="请选择罐箱类型"
          @change="changeTankType"
        >
          <el-option
            v-for="item in tankType"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="form.tankType === 'tankTank' ? '坦克罐' : '罐箱号'"
        prop="containerNo"
      >
        <el-select
          v-model="form.containerNo"
          filterable
          size="small"
          placeholder="请选择坦克罐"
          v-if="form.tankType === 'tankTank'"
        >
          <el-option
            v-for="item in tankList"
            :key="item.id"
            :label="item.tankNumber"
            :value="item.tankNumber"
          ></el-option>
        </el-select>
        <el-input
          placeholder="请输入罐箱号"
          v-model="form.containerNo"
          size="small"
          v-else
        ></el-input>
      </el-form-item>
      <el-form-item label="铅封号" prop="leadSealNumber">
        <el-input
          placeholder="请输入铅封号"
          v-model="form.leadSealNumber"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item
        label-width="120px"
        label="预计到厂时间"
        prop="expectedArrivalTimeAtTheFactory"
      >
        <el-date-picker
          v-model="form.expectedArrivalTimeAtTheFactory"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择预计到厂时间"
          size="small"
        >
        </el-date-picker>
      </el-form-item>
      <div class="from-header">物料</div>
      <el-table :data="form.materials" border style="width: 100%" class="table">
        <el-table-column prop="itemNo" label="行项目号"> </el-table-column>
        <el-table-column prop="matCode" label="物料"> </el-table-column>
        <el-table-column prop="matDesc" label="物料描述"> </el-table-column>
        <el-table-column prop="num" label="剩余数量"></el-table-column>
        <el-table-column prop="assignedNum" label="分配数量">
          <template slot-scope="scope">
            <el-form-item label-width="0">
              <el-input
                :disabled="type === 'edit' || splitOrder === '否'"
                type="number"
                min="1"
                :max="scope.row.num"
                v-model="scope.row.assignedNum"
                placeholder="请输入分配数量"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" v-noMoreClick @click="submit(false)"
        >保 存</el-button
      >
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  getDriverCarEscortList,
  update,
  transportUpdate,
  getTankType,
  waybillSupportsSplitting,
} from "@/api/transportation/demandorder";
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      form: {
        driverId: "", //司机id
        phone: "", //联系方式
        escortId: "", //押运员id
        carId: "", //车辆id
        trailerNo: "", //与车辆id绑定的挂车号
        bindCarNo: "", //挂车号
        containerNo: "", //罐箱号
        leadSealNumber: "", //铅封号
        expectedArrivalTimeAtTheFactory: "", //预计到厂时间
        materials: [], //物料
        requestId: "", //需求单id
        transportId: "", //运输单id
        transportNo: "", //运输单号
        tankType: "", //罐箱类型
      },
      driverList: [], //司机列表
      carList: [], //车辆列表
      trailerList: [], //挂车列表
      supercargoList: [], //押运员列表
      orderType: "", //货运订单类型
      type: "add",
      tankType: [],
      tankList: [],
      splitOrder: "是", // 是否支持拆单
    };
  },
  components: {},
  computed: {
    rules() {
      return {
        driverId: [
          { required: true, message: "请选择司机", trigger: "change" },
        ],
        // escortId: [
        //   { required: true, message: "请选择押运员", trigger: "change" },
        // ],
        carId: [{ required: true, message: "请选择车辆", trigger: "change" }],
        // tankType: [
        //   { required: true, message: "请选择罐箱类型", trigger: "change" },
        // ],
        bindCarNo: [
          {
            required: !this.form.trailerNo,
            message: "请选择挂车",
            trigger: "change",
          },
        ],
        // containerNo: [
        //   {
        //     required: true,
        //     message:
        //       this.form.tankType === "tankTank"
        //         ? "请选择坦克罐"
        //         : "请输入罐箱号",
        //     trigger: ["blur", "change"],
        //   },
        // ],
      };
    },
  },
  methods: {
    open(id, tmId, orderType, type, transportId, transportNo) {
      this.form = {
        driverId: "", //司机id
        phone: "", //联系方式
        escortId: "", //押运员id
        carId: "", //车辆id
        trailerNo: "", //与车辆id绑定的挂车号
        bindCarNo: "", //挂车号
        containerNo: "", //罐箱号
        leadSealNumber: "", //铅封号
        expectedArrivalTimeAtTheFactory: "", //预计到厂时间
        materials: [], //物料
        requestId: "", //需求单id
        transportId: "", //运输单id
        transportNo: "", //运输单号
        tankType: "", //罐箱类型
      };
      this.dialogVisible = true;
      this.loading = true;
      this.form.requestId = id;
      this.form.transportId = transportId;
      this.form.transportNo = transportNo;
      this.orderType = orderType;
      this.type = type;
      getTankType().then((res) => {
        if (res.data && res.status == 200) {
          this.tankType = res.data;
        }
      });
      waybillSupportsSplitting().then((res) => {
        if (res.data.code === 200 && res.data.success) {
          this.splitOrder = res.data.data;
        }
      });
      getDriverCarEscortList({
        id: id,
        tmId: tmId,
        transportId: transportId,
      }).then((res) => {
        this.loading = false;
        if (res.data.code === 200 && res.data.success) {
          const data = res.data.data;
          this.driverList = data.driver;
          this.carList = data.car;
          this.trailerList = data.trailer;
          this.tankList = data.tank;
          this.supercargoList = data.supercargoInfo;
          // 运单详情
          if (data.transportOrder) {
            for (let i in this.form) {
              this.form[i] = data.transportOrder[i] || this.form[i];
            }
            this.form.escortId = data.transportOrder.supercargoId || "";
            this.form.phone = data.transportOrder.driverPhone || "";
          }
          this.changeCar(this.form.carId);
          //运单物料
          let materials =
            this.type === "add" ? "demandOrderItems" : "transportOrderItems";
          this.form.materials = data[materials].map((item) => {
            return {
              id: item.id,
              itemNo: item.itemNo,
              matCode: item.matCode,
              matDesc: item.matDesc,
              num: item.num,
              assignedNum: item.num,
            };
          });
          // console.log(this.form);
        }
      });
    },
    changeCar(e) {
      for (let i in this.carList) {
        if (this.carList[i].id == e) {
          if (this.carList[i].bindCarNo) {
            this.form.trailerNo = this.carList[i].bindCarNo;
            this.form.bindCarNo = "";
          } else {
            this.form.trailerNo = "";
          }
        }
      }
    },
    changeDriver(e) {
      for (let i in this.driverList) {
        if (this.driverList[i].id == e) {
          this.form.phone = this.driverList[i].phone;
        }
      }
    },
    submit(whetherToMakeASingle) {
      for (let i in this.form.materials) {
        if (
          Number(this.form.materials[i].num) <
            this.form.materials[i].assignedNum ||
          !Number.isInteger(parseInt(this.form.materials[i].assignedNum)) ||
          this.form.materials[i].assignedNum <= 0
        ) {
          this.$message({
            message:
              "请输入正确的分配数量！（目前物料" +
              this.form.materials[i].matCode +
              "剩余数量为：" +
              this.form.materials[i].num +
              ")",
            type: "error",
            duration: 3000,
            showClose: true,
          });
          return false;
        }
      }
      this.$refs.form.validate((valid) => {
        let http = this.type === "add" ? update : transportUpdate;
        if (valid) {
          this.loading = true;
          let updateData = {
            ...this.form,
            whetherToMakeASingle: whetherToMakeASingle,
            materials: this.form.materials.map((item) => {
              return {
                id: item.id,
                num: item.assignedNum,
              };
            }),
            bindCarNo: this.form.trailerNo
              ? this.form.trailerNo
              : this.form.bindCarNo,
            id: this.form.transportId,
            transportNo: this.form.transportNo,
            demandId: this.form.requestId,
            supercargoId: this.form.escortId,
          };
          http(updateData).then(
            (res) => {
              this.loading = false;
              if (res.data.code === 200 && res.data.success) {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.dialogVisible = false;
                this.$emit("refresh");
                this.$refs.form.allDisabled = false;
                this.$refs.form.resetFields();
              } else if (res.data.code === 206) {
                this.$confirm(res.data.msg, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.submit(true);
                  })
                  .catch(() => {});
              }
            },
            (error) => {
              window.console.log(error);
              this.loading = false;
              this.$refs.form.allDisabled = false;
            }
          );
        } else {
          this.$message({
            message: "请填写必填项",
            type: "error",
          });
          return false;
        }
      });
    },
    changeTankType() {
      this.form.containerNo = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.assignWaybill {
  .from-header {
    width: 100%;
    display: flex;
    align-items: center;
    height: 36px;
    line-height: 36px;
    font-size: 14px;
    color: #666;
    border-bottom: 1px solid #eee;
    font-weight: bold;
    margin-bottom: 5px;
  }
  /deep/.el-form-item {
    width: 50%;
    margin-bottom: 10px;
  }
  /deep/.el-select {
    width: 100%;
  }
  /deep/.el-date-editor {
    width: 100%;
  }
  .table /deep/.el-form-item {
    width: 100%;
    margin-bottom: 0;
  }
}
</style>
